package com.zzw.interceptor;

import com.zzw.annotation.RequiresPermission;
import com.zzw.bean.Permissions;
import com.zzw.bean.Roles;
import com.zzw.dao.PermissionsMapper;
import com.zzw.service.RolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RolesService rolesService;
    @Autowired
    private PermissionsMapper permissionsMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是HandlerMethod类型（例如静态资源），直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        System.out.println("AuthInterceptor preHandle()被执行。。。");

        HttpSession session = request.getSession();


        //在这里判断是否已登录, 如果未登录, 打回登录页面.
        Integer userId = (Integer)session.getAttribute("userId");
        if (userId == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }

        //如果已登录. 判断所请求方法是否需要权限, 如果不需要权限, 放行.
        Method method = ((HandlerMethod) handler).getMethod();
        RequiresPermission requiresPermission = method.getDeclaredAnnotation(RequiresPermission.class);
        if (requiresPermission == null)  {
            return true;
        }

        //判断用户是否有该权限
        String permissionNeeded = requiresPermission.value();
        List<Roles> roles = rolesService.selectRolesByUserId(userId);
        for (Roles role : roles) {
            //查询角色权限列表
            List<Permissions> permissions = permissionsMapper.selectPermissionByRoleId(role.getId());
            for (Permissions permission : permissions) {
                if (permissionNeeded.equals(permission.getName())) {
                    return true;//查询到有该接口的访问权限, 放行
                }
            }
        }
        request.getRequestDispatcher("/unauthorized").forward(request, response);
        return false;//未查询到该接口的访问权限, 重定向到未授权页面.
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("AuthInterceptor postHandle()被执行。。。");
    }
}
